package com.erik.lin.domain;

/**
 * Created by Erik on 2017/7/10.
 */
public class Node2Tree {

    private Integer value;

    private Node2Tree leftSon;

    private Node2Tree rightSon;

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }

    public Node2Tree getLeftSon() {
        return leftSon;
    }

    public void setLeftSon(Node2Tree leftSon) {
        this.leftSon = leftSon;
    }

    public Node2Tree getRightSon() {
        return rightSon;
    }

    public void setRightSon(Node2Tree rightSon) {
        this.rightSon = rightSon;
    }

    public static void main(String[] args) {
        Integer[] nums = new Integer[]{1,2,3,4,5,6,7,8,9};
        Node2Tree root = new Node2Tree();
        for (Integer num: nums) {
            root.insert(num, root);
        }

        inOrderTraverse(root);
    }

    public Node2Tree find(Integer val, Node2Tree tree) {
        if(tree.getValue() == null) {
            return null;
        }
        if(val.equals(tree.getValue())) {
            return tree;
        }else if (val.intValue() < tree.getValue().intValue()) {
            return find(val, tree.getLeftSon());
        }else {
            return find(val, tree.getRightSon());
        }
    }

    public Node2Tree insert(Integer val, Node2Tree tree) {
        if(tree.getValue() == null) {
            tree.setValue(val);
            return tree;
        }
        if(val.equals(tree.getValue())) {
            return tree;
        }else if(val.intValue() < tree.getValue().intValue()) {
            tree.setLeftSon(new Node2Tree());
            return insert(val, tree.getLeftSon());
        }else {
            tree.setRightSon(new Node2Tree());
            return insert(val, tree.getRightSon());
        }
    }



    private static void preOrderTraverse(Node2Tree node) {
        if(node == null || node.getValue() == null) {
            return;
        }
        System.out.println(node.getValue());
        preOrderTraverse(node.getLeftSon());
        preOrderTraverse(node.getRightSon());
    }

    private static void inOrderTraverse(Node2Tree node) {
        if(node == null) {
            return;
        }
        inOrderTraverse(node.getLeftSon());
        System.out.println(node.getValue());
        inOrderTraverse(node.getRightSon());
    }

    private static void postOrderTraverse(Node2Tree node) {
        if(node == null) {
            return;
        }
        postOrderTraverse(node.getLeftSon());
        postOrderTraverse(node.getRightSon());
        System.out.println(node.getValue());
    }
}
